<template>
  <div class="a">
    <div class="app-container" ref="contractDetailContainer">
      <h2>合同详情</h2>

      <el-form :model="contractDetail" label-width="140px" class="mt-4">
        <el-form-item label="合同编号">
          {{ contractDetail.contractNo || "-" }}
        </el-form-item>
        <el-form-item label="老人姓名">
          {{ contractDetail.elderlyName || "-" }}
        </el-form-item>
        <el-form-item label="老人身份证号">
          {{ formatIdCard(contractDetail.idCard) || "-" }}
        </el-form-item>
        <el-form-item label="合同期限">
          {{ parseTime(contractDetail.startDate, "{y}-{m}-{d}") }}
          ——
          {{ parseTime(contractDetail.endDate, "{y}-{m}-{d}") }}
        </el-form-item>
        <!-- <el-form-item label="合同状态">
          <el-tag
            :type="
              contractDetail.contractStatus === '有效' ? 'success' : 'danger'
            "
          >
            {{ contractDetail.contractStatus || "-" }}
          </el-tag>
        </el-form-item> -->
        <el-form-item label="合同状态">
          <el-tag :type="getStatusTagType(contractDetail.contractStatus)">
            {{ contractDetail.contractStatus || "-" }}
          </el-tag>
        </el-form-item>
        <el-form-item label="签约时间">
          {{ parseTime(contractDetail.signTime, "{y}-{m}-{d} {h}:{i}") || "-" }}
        </el-form-item>
        <div v-if="contractDetail.partyCName&&contractDetail.partyCPhone!=null">
          <el-form-item label="丙方姓名">
          {{ contractDetail.partyCName || "-" }}
        </el-form-item>
        <el-form-item label="丙方联系方式">
          {{ contractDetail.partyCPhone || "-" }}
        </el-form-item>
        <el-form-item label="合同文件">
          {{ contractDetail.elderlyName }}长住合同.pdf        
          {{ contractDetail.contractFile || "-" }}
          <el-button type="text" @click="viewAgreement">查看</el-button>
        </el-form-item>
        </div>
      </el-form>
    </div>

    <!-- 解除记录：合同状态为已失效时显示 -->
    <div
      v-if="contractDetail.contractStatus === '已失效'"
      class="app-container mt-4"
    >
      <h2>解除记录</h2>
      <el-form label-width="140px" class="mt-4">
        <el-form-item label="提交人">
          {{ contractDetail.submitter || "-" }}
        </el-form-item>
        <el-form-item label="解除日期">
          {{ parseTime(contractDetail.releaseDate, "{y}-{m}-{d}") || "-" }}
        </el-form-item>
        <el-form-item label="解除协议">
          {{ contractDetail.elderlyName }}长住合同.pdf 
          <span>{{ contractDetail.agreementFile || "-" }}</span>
          <el-button type="text" @click="viewAgreement">查看</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>

  <el-button type="default" @click="handleGoBack" class="mt-6"
    >返回列表</el-button
  >
</template>

<script setup name="ContractView">
import { ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
// import { listContract } from "@/api/system/contract";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();
const contractDetail = ref({});
const contractName = ref("");
const contractDetailContainer = ref(null);

function getStatusTagType(status) {
  switch (status) {
    case "未生效":
      return "info";
    case "生效中":
      return "success";
    case "已过期":
      return "warning";
    case "已失效":
      return "danger";
    default:
      return "info";
  }
}

// 时间格式化函数
function parseTime(time, format = "{y}-{m}-{d} {h}:{i}:{s}") {
  if (!time) return "";
  const date = new Date(time);
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
  };
  return format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    return value.toString().padStart(2, "0");
  });
}

// 身份证号脱敏处理
function formatIdCard(idCard) {
  if (!idCard || idCard.length !== 18) return idCard;
  return idCard.slice(0, 6) + "********" + idCard.slice(14);
}

// 处理返回列表逻辑
function handleGoBack() {
  router.back(); // 修正为正确的返回方法
}

// 查看解除协议
function viewAgreement() {
  // 实际应用中可以根据协议文件地址进行预览或下载
  if (contractDetail.value.agreementFile) {
    // 示例：打开新窗口预览文件
    // window.open(`/api/file/preview?fileName=${contractDetail.value.agreementFile}`);
    ElMessage.info(`正在查看: ${contractDetail.value.agreementFile}`);
  } else {
    ElMessage.warning("没有可查看的协议文件");
  }
}

// 获取合同详情数据（包含解除记录）
// function fetchContractDetail(contractId) {
//   // 先清空现有数据，避免显示旧数据
//   contractDetail.value = {};

//   if (!contractId) {
//     ElMessage.warning("请选择有效的合同");
//     handleGoBack();
//     return;
//   }

//   listContract({ id: contractId })
//     .then((response) => {
//       if (response.rows && response.rows.length > 0) {
//         // 直接从合同详情中获取所有数据，包括解除记录相关字段
//         contractDetail.value = response.rows[0];
//       } else {
//         ElMessage.warning("未找到该合同信息");
//         handleGoBack();
//       }
//     })
//     .catch(() => {
//       ElMessage.error("获取合同详情失败");
//       handleGoBack();
//     });
// }

// 页面加载时获取数据
onMounted(() => {
  //   const contractId = route.query.contractId;
  //   contractName.value = route.query.contractName || "未知合同";
  //   fetchContractDetail(contractId);
  // });

  // // 监听路由参数变化，当合同ID改变时重新加载数据
  // watch(
  //   () => route.query.contractId,
  //   (newContractId, oldContractId) => {
  //     if (newContractId && newContractId !== oldContractId) {
  //       contractName.value = route.query.contractName || "未知合同";
  //       fetchContractDetail(newContractId);
  //     }
  //   }
  const contractData = route.query.contractData;
  if (contractData) {
    contractDetail.value = JSON.parse(contractData);
    contractName.value = route.query.contractName || "未知合同";
  } else {
    ElMessage.warning("未获取到合同信息");
    handleGoBack();
  }
});

// 监听路由参数变化（修改后）
watch(
  () => route.query.contractData,
  (newData, oldData) => {
    if (newData && newData !== oldData) {
      contractDetail.value = JSON.parse(newData);
      contractName.value = route.query.contractName || "未知合同";
    }
  }
);
</script>

<style scoped>
.mt-4 {
  margin-top: 16px;
}
.el-form-item__label {
  color: #a9a9a9;
}
.app-container {
  height: auto;
  width: 100%;
  border: 1px solid #e6e6e6;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin: 20px;
  padding: 20px;
}
body {
  background-color: #f1f2f5;
}
.a {
  height: auto;
  width: 100%;
  background-color: #fff;
  padding: 20px;
}
.mt-6 {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  width: 100px;
  background-color: #0052d9;
  color: white;
  margin: 20px auto;
}
</style>
